package ucap.com.lesanapp.base.impl;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Vibrator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import ucap.com.lesanapp.R;
import ucap.com.lesanapp.activitys.LeaderListActivity;
import ucap.com.lesanapp.activitys.NewsDetailedActivity;
import ucap.com.lesanapp.base.BasePager;
import ucap.com.lesanapp.bean.DateBean;
import ucap.com.lesanapp.bean.LeaderBean;
import ucap.com.lesanapp.global.Constants;
import ucap.com.lesanapp.global.SettingsModelState;
import ucap.com.lesanapp.utils.NetworkStateUtils;
import ucap.com.lesanapp.utils.PrefUtils;
import ucap.com.lesanapp.view.WebViewDialog;


/**
 * Created by Administrator on 2016/7/27.
 */
public class LeaderBase extends BasePager implements View.OnClickListener {
    @Bind(R.id.ll_leader_loading)
    LinearLayout llLoading;
    @Bind(R.id.sr_leader_refresh)
    SwipeRefreshLayout sRefresh;
    @Bind(R.id.lv_leader)
    ListView lvContent;

    ArrayList<DateBean.RowsBean> mListDate;
    ArrayList<LeaderBean.RowsBean> mListLeader;
    private MyAdapter adapter;
    private HttpUtils utils;
    private int model;
    private int networkType;
    private LinearLayout llLeft;
    private LinearLayout llRight;
    HashMap<String, String> laderId = new HashMap<>();

    public LeaderBase(Activity mActivity) {
        super(mActivity);
    }

    @Override
    public void intiDate() {
        View view = View.inflate(mActivity, R.layout.base_leader, null);
        ButterKnife.bind(this, view);
        flContent.addView(view);
        View viewHead = View.inflate(mActivity, R.layout.leader_top, null);
        llLeft = (LinearLayout) viewHead.findViewById(R.id.ll_left);
        llRight = (LinearLayout) viewHead.findViewById(R.id.ll_right);
        lvContent.addHeaderView(viewHead);
        mListLeader = new ArrayList<>();
        mListDate = new ArrayList<>();
        String topCache = PrefUtils.getString("leader_position", "", mActivity);
        if (!topCache.isEmpty()) {
            analysisDateLeader(topCache);
        }
        getTopDate();

    }

    @Override
    public void intiDateForService() {

        adapter = new MyAdapter();
        lvContent.setAdapter(adapter);
        //刷新数据
        sRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
//                getDateZhangTong();//刷新列表数据
//                getTopDate();
                getType();//重新获取浏览模式和网络环境
                getTopDate();//从新获取头部数据
                sRefresh.setRefreshing(false);
            }
        });
        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //减去头部句id
                int index = position - 1;
                //避免用户点击底部发生角标越界
                if (index < mListDate.size() && index >= 0) {
                    String cid = "";
                    DateBean.RowsBean item = adapter.getItem(index);
                    String title = item.getTITLE();
                    for (int i = 0; i < mListLeader.size(); i++) {//通过判断标题里面是否包含领导名字而取的对应id
                        String name = mListLeader.get(i).getNAME();
                        if (title.indexOf(name) != -1) {
                            cid = mListLeader.get(i).getID();
                        }
                    }
                    Intent intent = new Intent(mActivity, NewsDetailedActivity.class);
                    intent.putExtra("title", item.getCHANNELNAME());
                    intent.putExtra("code", item.getID());
                    intent.putExtra("head", item.getTITLE());
//                    intent.putExtra("cid", item.getCID());
                    intent.putExtra("cid", cid);
                    mActivity.startActivity(intent);
                }
            }
        });
        lvContent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Vibrator vibrator = (Vibrator) mActivity.getSystemService(mActivity.VIBRATOR_SERVICE);
                vibrator.vibrate(60);
                int index = position - 1;
                if (index >= 0 && index < mListDate.size()) {
                    String cid = "";
                    DateBean.RowsBean item = adapter.getItem(index);
                    String title = item.getTITLE();
                    for (int i = 0; i < mListLeader.size(); i++) {//通过判断标题里面是否包含领导名字而取的对应id
                        String name = mListLeader.get(i).getNAME();
                        if (title.indexOf(name) != -1) {
                            cid = mListLeader.get(i).getID();
                        }
                    }
                    WebViewDialog.showDialog(mActivity, item.getID(), item.getTITLE(), cid);
                }
                return true;
            }
        });
        getType();
    }

    /**
     * 获取头部领导的数据
     */
    public void getTopDate() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpMethod.GET, Constants.LeaderURL.LEADER_DATES, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                analysisDateLeader(responseInfo.result);
                Log.i("leaderHeadData", responseInfo.result);
                PrefUtils.putString("leader_position", responseInfo.result, mActivity);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                llLoading.setVisibility(View.INVISIBLE);
            }
        });
    }

    /**
     * 解析头部数据
     *
     * @param date
     */
    private void analysisDateLeader(String date) {
        mListLeader.clear();//清除旧数据,以免出现重复数据
        llRight.removeAllViews();
        llLeft.removeAllViews();
        Gson gson = new Gson();
        LeaderBean leader = gson.fromJson(date, LeaderBean.class);
        mListLeader.addAll(leader.getRows());
        addTopLeaderItem();
        //获取领导list数据的时候先清空旧数据，避免出现重复数据
        getDateFroService();//获取领导数据
    }

    /**
     * 拆分所有领导的数据为左右两个list
     */
    private void addTopLeaderItem() {
        for (int i = 0; i < mListLeader.size(); i++) {
            if (i % 2 == 0) {
                //左边领导布局
                Button button = new Button(mActivity);
                final LeaderBean.RowsBean rowsBean = mListLeader.get(i);
                button.setText(rowsBean.getNAME());
                button.setTextColor(Color.WHITE);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(10, 5, 5, 5);
                button.setLayoutParams(lp);
                button.setBackgroundResource(R.drawable.selecter_bg_btn);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, LeaderListActivity.class);
                        intent.putExtra("name", rowsBean.getNAME());
                        intent.putExtra("cacheName", rowsBean.getNAME());
                        intent.putExtra("cid", rowsBean.getID());
                        intent.putExtra("sid", rowsBean.getSID());
                        intent.putExtra("uri", Constants.LeaderURL.LEADER_DATES_POSITION + rowsBean.getID() + "&&num=30");
                        mActivity.startActivity(intent);
                    }
                });
                llLeft.addView(button);
            } else {
                //中间的领导数据
                Button button = new Button(mActivity);
                final LeaderBean.RowsBean rowsBeanRight = mListLeader.get(i);
                button.setText(rowsBeanRight.getNAME());
                button.setTextColor(Color.WHITE);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(5, 5, 5, 5);
                button.setLayoutParams(lp);
                button.setBackgroundResource(R.drawable.selecter_bg_btn);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mActivity, LeaderListActivity.class);
                        intent.putExtra("name", rowsBeanRight.getNAME());
                        intent.putExtra("cacheName", rowsBeanRight.getNAME());
                        intent.putExtra("cid", rowsBeanRight.getID());
                        intent.putExtra("sid", rowsBeanRight.getSID());
                        intent.putExtra("uri", Constants.LeaderURL.LEADER_DATES_POSITION + rowsBeanRight.getID() + "&&num=30");
                        mActivity.startActivity(intent);
                    }
                });
                llRight.addView(button);
            }
        }
    }


    @Override
    public void onClick(View v) {

    }

    /**
     * 判断网络网络环境以及,阅读模式
     */
    public void getType() {
        model = PrefUtils.getInt("model", SettingsModelState.MODEL_TEXT_AND_IMAGE, mActivity);
        Log.i("model", model + "模式");
        networkType = NetworkStateUtils.network(mActivity);
        Log.i("model", networkType + "网络状态");
    }

    /**
     * 从服务器获取数据
     */

    public void getDateFroService() {
        mListDate.clear();//清空旧数据
        utils = new HttpUtils();

        for (int i = 0; i < mListLeader.size(); i++) {
            final LeaderBean.RowsBean rowsBean = mListLeader.get(i);
//            Log.i("leaderList", rowsBean.getID());
            utils.send(HttpMethod.GET, Constants.LeaderURL.LEADER_DATES_POSITION + rowsBean.getID() + "&&num=4", new RequestCallBack<String>() {
                @Override
                public void onSuccess(ResponseInfo<String> responseInfo) {
                    analysisDate(responseInfo.result, rowsBean.getID(), rowsBean.getNAME());

                    PrefUtils.putString("leaderData", responseInfo.result, mActivity);
                }

                @Override
                public void onFailure(HttpException error, String msg) {

                }
            });
        }

    }


    /**
     * 解析数据
     */
    private void analysisDate(String result, String id, String name) {
        Gson gson = new Gson();
        DateBean date = gson.fromJson(result, DateBean.class);
        mListDate.addAll(date.getRows());
        laderId.put(name, id);
        adapter.notifyDataSetChanged();

    }

    class MyAdapter extends BaseAdapter {
        BitmapUtils bitmapUtils;

        MyAdapter() {
            bitmapUtils = new BitmapUtils(mActivity);
        }

        @Override
        public int getCount() {
            return mListDate.size();
        }

        @Override
        public DateBean.RowsBean getItem(int position) {
            return mListDate.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(mActivity, R.layout.item_date_content, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            DateBean.RowsBean date = getItem(position);
            Log.i("leaderImagePath", date.getPATHANDURL());
            //判断服务器是否返回图片，没有就影藏图片控件
            if (!date.getPATHANDURL().isEmpty()) {
                //图文模式
                if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
                    holder.ivPhoto.setVisibility(View.VISIBLE);
                    bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                } else if (model == SettingsModelState.MODEL_TEXT) {
                    //文本模式
                    holder.ivPhoto.setVisibility(View.GONE);
                } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
                    //智能模式
                    if (networkType == ConnectivityManager.TYPE_WIFI) {
                        //wifi状态
                        holder.ivPhoto.setVisibility(View.VISIBLE);
                        bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                    } else {
                        holder.ivPhoto.setVisibility(View.GONE);
                    }
                }
            } else {
                holder.ivPhoto.setVisibility(View.GONE);
            }
            holder.tvTitle.setText(date.getTITLE());
            holder.tvTime.setText(date.getTIME());
            holder.tvType.setText(date.getCHANNELNAME());
            return convertView;
        }
    }

    public class ViewHolder {
        @Bind(R.id.iv_news_photo)
        ImageView ivPhoto;
        @Bind(R.id.tv_news_title)
        TextView tvTitle;
        @Bind(R.id.tv_news_time)
        TextView tvTime;
        @Bind(R.id.tv_news_type)
        TextView tvType;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

}
